import json
from django.http import JsonResponse
from django.shortcuts import render
from django.views import View
from .models import UserProfile
import hashlib
from django.utils.decorators import method_decorator
from tools.logging_dec import logging_check
import random
from django.core.cache import cache
from tools.sms import YunTongXin
from .tasks import send_sms_c
from dtoken import views


# 异常码 10100 -- 10199

# Create your views here.


# 装饰器校验登录状态及判断登录状态后的头像修改
@logging_check
def users_views(request, username):
    # 修改头像      对应change_info的HTML    API:http://127.0.0.1:8000/v1/users/<str:username>/avatar
    if request.method != 'POST':
        result = {'code': 10202, 'error': 'place use POST'}
        return JsonResponse(result)

    user = request.myuser
    avatar = request.FILES['avatar']
    user.avatar = avatar
    user.save()
    return JsonResponse({'code': 200})


class UserViews(View):
    # 定义一个视图类

    # 提取数据，用于数据显示页。对应about的HTML
    def get(self, request, username=None):
        # /v1/users/username
        if username:
            try:
                user = UserProfile.objects.get(username=username)
            except Exception as e:
                result = {'code': 10120, 'error': 'The username is wrong'}
                return JsonResponse(result)
                print('result')
            result = {'code': 200, 'username': username,
                      'data': {'info': user.info, 'sign': user.sign, 'nickname': user.nickname,
                               'avatar': str(user.avatar)}}
            return JsonResponse(result)

        else:
            # /v1/users
            pass
        return JsonResponse({'code': 200, 'msg': 'test'})

    def post(self, request):
        # 用户信息注册    对应register的HTML   API：http://127.0.0.1:8000/v1/users

        json_str = request.body
        print('json_str')
        json_obj = json.loads(json_str)
        username = json_obj['username']
        email = json_obj['email']
        password_1 = json_obj['password_1']
        password_2 = json_obj['password_2']
        phone = json_obj['phone']
        sms_num = json_obj['sms_num']
        # print(json_str)

        # 参数基本检查两次密码校验
        if password_2 != password_1:
            result = {'code': 10100, 'error': 'The password is not same'}
            return JsonResponse(result)
        #     # 检查手机号是否唯一，一个手机号只能注册一次
        # old_phone = UserProfile.objects.filter(phone=phone)
        # if old_phone:
        #     result = {'code': 10102, 'error': 'The phone is exists'}
        #     return JsonResponse(result)

        # 验证码的校验
        old_code = cache.get('sms_%s' % (phone))
        if not old_code:
            result = {'code': 10018, 'error': 'The code is wrong'}
            return JsonResponse(result)
        if int(sms_num) != old_code:
            result = {'code': 10019, 'error': 'The code is wrong'}
            return JsonResponse(result)

        # 检查用户名是否可用
        old_users = UserProfile.objects.filter(username=username)
        print(old_users)
        if old_users:
            result = {'code': 10101, 'error': 'The username is already existed'}
            return JsonResponse(result)

        # UserProfile插入数据（密码MD5存储）
        p_m = hashlib.md5()
        p_m.update(password_1.encode())
        # 存入数据库
        UserProfile.objects.create(username=username, nickname=username, password=p_m.hexdigest(), email=email,
                                   phone=phone)
        # 记录会话状态，注册免登陆一天
        token = views.make_token(username)

        result = {'code': 200, 'username': username, 'data': {'token': token}}
        return JsonResponse(result)

    #
    #
    #     # 更新用户数据 【只更新：昵称，个人签名，个人描述】  对应chanage_info   API:http://127.0.0.1:8000/v1/users/<str:username>
    @method_decorator(logging_check)
    def put(self, request, username=None):
        # 更新用户数据 【只更新：昵称，个人签名，个人描述】
        # 从前端取出数据
        json_str = request.body
        json_obj = json.loads(json_str)
        # 取user对象
        user = request.myuser
        user.sign = json_obj['sign']
        user.info = json_obj['info']
        user.nickname = json_obj['nickname']
        user.save()
        return JsonResponse({'code': 200})

# 异常码 10100 -- 10199


def sms_view(request):
    # 验证码的（产生，存储，发送）  对应register的HTML    API：http://127.0.0.1:8000/v1/users/sms
        if request.method != 'POST':
            result = {'code': 10070, 'error': 'Please use post'}
            return JsonResponse(result)

        json_str = request.body
        json_obj = json.loads(json_str)
        phone = json_obj['phone']
        print(phone)

        # 生成随机码
        code = random.randint(1000, 9999)
        print('phone:', phone, 'code:', code)

        # 利用缓存技术存储随机码    django-redis
        cache_key = 'sms_%s'%(phone)
        # 检查是否已经有发过的且未过期的验证码
        old_code = cache.get(cache_key)
        if old_code:
            return JsonResponse({'code': 10199, 'error': 'The code is already existed'})


        cache.set(cache_key, code, 60)
        # 发送随机码
        # send_msm(phone, code)     # django自定义版
        send_sms_c.delay(phone, code)       # celery
        return JsonResponse({'code': 200})

# 调用sms类方法
def send_sms(phone, code):


    config = {
        "accountSid": "8a216da88185a9c00181a9046c1a0767",
        "accountToken": "aa68731ea7ce487caf1eb8e7c686eea9",
        "appId": "8a216da88185a9c00181a9046d22076e",
        "templateId": "1",
    }

    yun = YunTongXin(**config)
    res = yun.run(phone, code)
    return res
